package com.handong.handserialprogram.utils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.thread.InputMethod;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 简单工具类。
 *
 * @author tang-xdong
 *         <p>
 *         2015-11-4
 */
public class AppUtil {

    private static final String TAG = "AppUtil";
    private static Toast mShortToast;
    private static Toast mLengthToast;

    /**
     * 判断是否有可用的网络。
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager
                    .getActiveNetworkInfo();
            if (networkInfo != null) {
                return networkInfo.isAvailable();
            }
        }
        showLengthToast(context, "无可用的网络连接");
        return false;
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOPen(final Context context) {
        LocationManager locationManager
                = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {

    }
    /**
     * 强制帮用户打开WIFI
     * @param context
     */
    public static void openWifi(Context context) {
        WifiManager wifiManager =(WifiManager)context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null && !wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
    }

    public static void showShortToast(Context context, String message) {
        if (mShortToast == null) {
            mShortToast = Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT);
        } else {
            mShortToast.setText(message);
            mShortToast.setDuration(Toast.LENGTH_SHORT);
        }
        mShortToast.show();
    }

    public static void showLengthToast(Context context, String message) {
        if (mLengthToast == null) {
            mLengthToast = Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG);
        } else {
            mLengthToast.setText(message);
            mLengthToast.setDuration(Toast.LENGTH_LONG);
        }
        mLengthToast.show();
    }

    public static void cancelToast() {
        if (mShortToast != null) {
            mShortToast.cancel();
            mShortToast = null;
        }

        if (mLengthToast != null) {
            mLengthToast.cancel();
            mLengthToast = null;
        }
    }

    /**
     * 打开新的activity，并添加动画。
     *
     * @param activity
     * @param T
     * @param pairs
     */
//	public static void startAct(Activity activity, Class<?> T,
//			BasicNameValuePair... pairs) {
//		startAct(activity, T, null, pairs);
//	}

//	public static void startAct(Activity activity, Class<?> T, Bundle bundle,
//			BasicNameValuePair... pairs) {
//		Intent intent = new Intent();
//		intent.setClass(activity, T);
//		if (pairs != null && pairs.length != 0) {
//			for (int i = 0; i < pairs.length; i++) {
//				intent.putExtra(pairs[i].getName(), pairs[i].getValue());
//			}
//		}
//		if (bundle != null) {
//			intent.putExtras(bundle);
//		}
//		activity.startActivity(intent);
//		activity.overridePendingTransition(R.anim.push_left_in,
//				R.anim.push_left_out);
//	}

    /**
     * 关闭activity，同样加上关闭动画。
     *
     * @param activity
     */
    public static void finishAct(Activity activity) {
        activity.finish();
        activity.overridePendingTransition(R.anim.push_right_in,
                R.anim.push_right_out);
    }

    /**
     * 判断是否为格式正确的ip地址。
     *
     * @param ip
     * @return
     */
    public static boolean isCorrectInternetAddress(String ip) {
        try {
            String temp = ip.trim();
            String[] ipArray = temp.split("\\.");
            int len = ipArray.length;
            if (len == 4) {
                for (int i = 0; i < len; i++) {
                    int tempInt = Integer.parseInt(ipArray[i]);
                    if (tempInt < 0 || tempInt > 255) {
                        return false;
                    }
                }
            } else
                return false;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    public static boolean isCorrectInternetAddressByMatch(String ipAddress) {

        String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
                + "(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
        Pattern pattern = Pattern.compile(ip);
        Matcher matcher = pattern.matcher(ipAddress);

        return matcher.matches();
    }

    /**
     * 根据出生日期，计算年龄。
     *
     * @param birthStr
     * @return
     */
    public static String computeAge(String birthStr) {
        String[] birth = birthStr.split("-");
        int yearBirth = Integer.parseInt(birth[0]);
        int monthBirth = Integer.parseInt(birth[1]);
        int dayBirth = Integer.parseInt(birth[2]);

        Calendar calendar = Calendar.getInstance();
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayNow = calendar.get(Calendar.DAY_OF_MONTH);

        if (yearBirth >= yearNow) {
            return "";
        }
        int age = yearNow - yearBirth;
        if (monthBirth >= monthNow) {
            if (monthBirth == monthNow) {
                if (dayBirth > dayNow) {
                    age--;
                }
            } else {
                age--;
            }
        }
        return String.valueOf(age);
    }

    /**
     * 获取版本号。
     *
     * @param context
     * @return 应用版本号。
     */
    public static String getVersion(Context context) {
        PackageManager manager = context.getApplicationContext().getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return version;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void showSoftInput(EditText editText) {
        InputMethod method = new InputMethod(editText);
        editText.post(method);
    }

    public static void hideSoftInput(Context context, Window window) {
        InputMethodManager manager = (InputMethodManager) context.getApplicationContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (manager != null && manager.isActive()) {
            manager.hideSoftInputFromWindow(window.getDecorView().getWindowToken(), 0);
        }
    }

    public static void exit() {
        if (mShortToast != null) {
            mShortToast.cancel();
            mShortToast = null;
        }
    }
    //锁屏
    public static  void setKeyguardEnable(Activity activity,boolean enable) {
        //disable
        if (!enable) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                    WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
            return;
        }
        //enable
        activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    }

    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
                int count=is.read(bytes, 0, buffer_size);
                if(count==-1)
                    break;
                os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale+0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}
